﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

using CMN.Models;
using CMN.Models.Interfaces;
using CMN.Entity;
using System.Web.Routing;
using CMN.Common;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using CMN.Controllers.Filters;
using System.IO;
using System.Xml;
namespace CMN.Controllers
{
    [ExceptionFilter]
    [LoggerFilter]
    [UserAuthorize]
    public class Normal_TemplatesController : Controller
    {
        
        // 返回json字符串
        protected string returnJson = string.Empty;

        /// <summary>
        /// 转到View页面
        /// </summary>
        /// <returns></returns>
        public ViewResult Index()
        {
            return View("Index");//页面地址
        }

        /// <summary>
        /// 返回模板方案列表
        /// </summary>
        /// <returns>json</returns>
        public string List(string actionId)
        {
            QueryParam qp = new QueryParam();
            int recordNum = 0;
            IsoDateTimeConverter jsDataConvert = new Newtonsoft.Json.Converters.IsoDateTimeConverter();
            jsDataConvert.DateTimeFormat = "yyyy-MM-dd";
            IDataService<Normal_TemplatesEntity> Normal_TemplatesSv = ServiceBuilder.BuildNormal_TemplatesService();
            //返回json数组
            if (actionId == "m")
            {
                List<Normal_TemplatesEntity> normal_templatesList = Normal_TemplatesSv.List(qp, out recordNum);
                Normal_TemplatesEntity template=new Normal_TemplatesEntity();
                template.Id=0;
                template.Title="默认模板";
                template.Info="默认模板";
                normal_templatesList.Insert(0, template);
                returnJson = string.Concat("{totalPorperty:", recordNum, ",root:", JsonConvert.SerializeObject(normal_templatesList, Newtonsoft.Json.Formatting.Indented, jsDataConvert), "}");
            }
            else
            {
                int pageSize = (int)Utils.GetQueryAndFormString("limit", this, 4, 1, DataType.Int);
                int pageIndex = (int)Utils.GetQueryAndFormString("start", this, 9, 1, DataType.Int);

                qp.PageIndex = pageIndex / pageSize + 1; ;
                qp.PageSize = pageSize;
                List<Normal_TemplatesEntity> normal_templatesList = Normal_TemplatesSv.List(qp, out recordNum);
                returnJson = string.Concat("{totalPorperty:", recordNum, ",root:", JsonConvert.SerializeObject(normal_templatesList, Newtonsoft.Json.Formatting.Indented, jsDataConvert), "}");

            }

         
           
            return returnJson;

        }

        /// <summary>
        /// 查看模板方案 
        /// </summary>
        /// <param name="id"></param>
        /// <returns>json</returns>
        public string Look(string actionId)
        {
           IDataService<Normal_TemplatesEntity> Normal_TemplatesSv = ServiceBuilder.BuildNormal_TemplatesService();
            int intId=Utils.StringToInt(actionId,0);
            Normal_TemplatesEntity normal_templates = Normal_TemplatesSv.Look(intId);
            if (normal_templates != null)
                returnJson = string.Concat("{success:true,data:", JsonConvert.SerializeObject(normal_templates), "}");
            else
                returnJson = "{success:'false'}";
            return returnJson;
        }
         private void updateTemplateList(Normal_TemplatesEntity normal_template)
        {
            string searchPath = Utils.GetServerPath() + normal_template.Dir;
            List<string> files = Utils.GetDirectoryFileNames(searchPath, ".htm");
            IDataService<Normal_TemplateListEntity> templateListEntitySv=ServiceBuilder.BuildNormal_TemplateListService();
            IDataService<Normal_TemplateTypeEntity> tmpTypeSv = ServiceBuilder.BuildNormal_TemplateTypeService();
             QueryParam qp=new QueryParam();
             int recordCount=0;
             List<Normal_TemplateTypeEntity> tmpTypeList = tmpTypeSv.List(qp, out recordCount);
            Normal_TemplateListEntity tmpListEntity = new Normal_TemplateListEntity();
            foreach (string str in files)
            {
                tmpListEntity = new Normal_TemplateListEntity();
                tmpListEntity.Enabled = true;
                tmpListEntity.ModuleType = str.Substring(str.LastIndexOf('\\')+1, (str.Length - str.LastIndexOf('\\')-1)).Replace(".htm", "").ToLower();
                tmpListEntity.TemplateId = normal_template.Id;
                tmpListEntity.IsDefault = true;
                tmpListEntity.TemplateName = str.Substring(str.LastIndexOf('\\') + 1, (str.Length - str.LastIndexOf('\\') - 1));
                tmpListEntity.TemplateTitle = normal_template.Info+getTemplateTitle(tmpTypeList, tmpListEntity.ModuleType);
                tmpListEntity.DataTable_Action=normal_template.DataTable_Action;
                if(normal_template.DataTable_Action==DataTableAction.Insert)
                templateListEntitySv.Insert(tmpListEntity);
                else 
                    templateListEntitySv.Update(tmpListEntity);
                
            }
            
        }

         protected string getTemplateTitle(List<Normal_TemplateTypeEntity> tmpTypeList,string tmpType)
         {
             string strRetrun = string.Empty;
             foreach (Normal_TemplateTypeEntity tmp in tmpTypeList)
             {
                 if (tmp.TemplateType == tmpType.ToLower())
                 {
                     strRetrun= tmp.TemplateTypeName;
                     break;
                 }
             }
             if (string.IsNullOrEmpty(strRetrun))
             {
                 strRetrun = "其他";
             }
             return strRetrun;
         }


        /// <summary>
        /// 更新模板方案
        /// </summary>
        /// <param name="id"></param>
        /// <returns>json</returns>
        public string Update(string actionId)
        {
            int intId = Utils.StringToInt(actionId,0);
            if (intId != 0)
            {
                ISearchDataService<Normal_TemplatesEntity> Normal_TemplatesSv = ServiceBuilder.BuildNormal_TemplatesService();
                Normal_TemplatesEntity normal_template = null;
                normal_template = Normal_TemplatesSv.Look(intId);
                if (normal_template == null)
                {
                    returnJson = "{success:'false',message:'没有该模板信息'}";
                }
                else
                {
                    XmlHelper xmlhelper = new XmlHelper();
                    string strFilePath = string.Concat(string.Concat(Utils.GetServerPath(),normal_template.Dir, "\\", "templates.config"));

                    xmlhelper.Load(strFilePath);
                    ISearchDataService<Normal_SkinEntity> skinSv = ServiceBuilder.BuildNormal_SkinService();
                    if (System.IO.File.Exists(strFilePath))
                    {


                        normal_template.DataTable_Action = DataTableAction.Update;
                        normal_template.Title = xmlhelper.GetAttribValue("root/template", "name");
                        normal_template.Info = xmlhelper.GetAttribValue("root/template", "info");
                        if (xmlhelper.GetAttribValue("root/template", "isDefault") == "true")
                            normal_template.IsDefault = true;
                        else
                            normal_template.IsDefault = false;
                        Normal_TemplatesSv.Update(normal_template);
                        XmlNodeList nodeList = xmlhelper.GetList("root/template/skin");
                        int skinId = 0;
                        Normal_SkinEntity skin = null;
                        foreach (XmlNode node in nodeList)
                        {

                            skin = skinSv.Look(normal_template.SkinID);
                            if (skin != null && skin.Dir == string.Concat(normal_template.Dir, "\\", node.Attributes["dir"].Value))
                            {
                                skin.DataTable_Action = DataTableAction.Update;
                                
                                skin.Title = node.Attributes["name"].Value;
                                skinSv.Update(skin);
                            }
                            else
                            {
                                skin = new Normal_SkinEntity();
                                skin.Dir = string.Concat(normal_template.Dir, "\\", node.Attributes["dir"].Value);

                                skin.DataTable_Action = DataTableAction.Insert;
                                skin.TemplateID = Normal_TemplatesSv.IsHas(normal_template.Dir);
                                skin.Title = node.Attributes["name"].Value;
                                skinId = skinSv.IsHas(skin.Dir.Replace("\\","\\\\"));
                                if (skinId <= 0)  //是否已有该模板皮肤
                                {
                                    skinSv.Insert(skin);
                                    if (node.Attributes["default"].Value == "true")
                                    {
                                        normal_template.SkinID = skinSv.IsHas(skin.Dir.Replace("\\", "\\\\"));
                                        normal_template.Id = skin.TemplateID;
                                        normal_template.DataTable_Action = DataTableAction.Update;
                                        Normal_TemplatesSv.Update(normal_template);
                                    }
                                }
                                else
                                {
                                    skin.Id = skinId;
                                    skinSv.Update(skin);
                                    if (normal_template.SkinID != skinId)
                                    {
                                        if (node.Attributes["default"].Value == "true")
                                        {
                                            normal_template.SkinID = skinId;
                                            normal_template.Id = skin.TemplateID;
                                            normal_template.DataTable_Action = DataTableAction.Update;
                                            Normal_TemplatesSv.Update(normal_template);
                                        }
                                    }
                                }
                            }
                        }

                    }



                    xmlhelper.Dispose();
                    returnJson = "{success:'true',message:'更新成功'}";

                }
            }
            else
            {
                returnJson = "{success:'false',message:'错误的模板编号'}";
            }

            return returnJson;
        }

        /// <summary>
        /// 新增模板方案
        /// </summary>
        /// <returns>json</returns>
        public string Insert()
        {

            ISearchDataService<Normal_TemplatesEntity> Normal_TemplatesSv = ServiceBuilder.BuildNormal_TemplatesService();
            string[] dirInfos = Directory.GetDirectories(string.Concat(Utils.GetServerPath(), "templates"));
            string strFilePath = string.Empty;

            XmlHelper xmlhelper = new XmlHelper();
            bool ifAdd = false;
            string strSaveDir = string.Empty;
            for (int i = 0; i < dirInfos.Length; i++)
            {

                strSaveDir = string.Concat("templates", dirInfos[i].Substring(dirInfos[i].LastIndexOf('\\'), (dirInfos[i].Length - dirInfos[i].LastIndexOf('\\'))));
                strFilePath = string.Concat(dirInfos[i].ToString(), "\\", "templates.config");
                if (Normal_TemplatesSv.IsHas(strSaveDir) <= 0)
                {
                    xmlhelper.Load(strFilePath);
                    ISearchDataService<Normal_SkinEntity> skinSv = ServiceBuilder.BuildNormal_SkinService();
                    if (System.IO.File.Exists(strFilePath))
                    {
                        ifAdd = true;

                        Normal_TemplatesEntity template = new Normal_TemplatesEntity();
                        template.DataTable_Action = DataTableAction.Insert;
                        template.Dir = strSaveDir;
                        template.Title = xmlhelper.GetAttribValue("root/template", "name");
                        template.Info = xmlhelper.GetAttribValue("root/template", "info");
                        if (xmlhelper.GetAttribValue("root/template", "isDefault")!=null && xmlhelper.GetAttribValue("root/template", "isDefault") == "true")
                            template.IsDefault = true;

                        Normal_TemplatesSv.Insert(template);
                        updateTemplateList(template);
                        XmlNodeList nodeList = xmlhelper.GetList("root/template/skin");
                        Normal_SkinEntity skin = null;
                        foreach (XmlNode node in nodeList)
                        {
                            skin = new Normal_SkinEntity();
                            skin.DataTable_Action = DataTableAction.Insert;
                            skin.TemplateID = template.Id;
                            skin.Title = node.Attributes["name"].Value;
                            skin.Dir = string.Concat(template.Dir, "\\", node.Attributes["dir"].Value);
                            skinSv.Insert(skin);
                            if (node.Attributes["default"].Value == "true")
                            {
                                template.SkinID = skin.Id;
                                template.DataTable_Action = DataTableAction.Update;
                                Normal_TemplatesSv.Update(template);
                            }
                        }

                    }
                }

            }
            xmlhelper.Dispose();
            if (ifAdd)
            {
                returnJson = "{success:'true',message:'添加成功'}";
            }
            else
            {
                returnJson = "{success:'false',message:'没有要添加的模板'}";
            }

            return returnJson;

        }

        /// <summary>
        /// 删除模板方案
        /// </summary>
        /// <param name="id"></param>
        /// <returns>json</returns>
        public string Delete(string actionId)
        {
            int intId = Utils.StringToInt(actionId,0);
            if (intId != 0)
            {
                Normal_TemplatesEntity normal_templates = new Normal_TemplatesEntity();
                normal_templates.Id = intId;
                IDataService<Normal_TemplatesEntity> Normal_TemplatesSv = ServiceBuilder.BuildNormal_TemplatesService();

                if (Normal_TemplatesSv.Delete(normal_templates) == "")
                {

                    returnJson = "{success:'true'}";
                }
                else
                    returnJson = "{success:'false'}";
            }
            else
            {
                returnJson = "{success:'false'}";
            }
            return returnJson;
        }

        /// <summary>
        /// 批量删除模板方案
        /// </summary>
        /// <param name="idList">id列表 234_4_5</param>
        /// <returns>json</returns>
        public string DeleteList(string actionId)
        {
            Common.RegExpression.NumAndBarRegExpression regex = new CMN.Common.RegExpression.NumAndBarRegExpression();
            if (regex.IsMatch(actionId))
            {

                IDataService<Normal_TemplatesEntity> Normal_TemplatesSv = ServiceBuilder.BuildNormal_TemplatesService();
                if (Normal_TemplatesSv.DeleteList(actionId) == "")
                {
                    returnJson = "{success:'true'}";
                }
                else
                    returnJson = "{success:'false'}";

            }
            else
            {
                returnJson = "{success:'false',message:'参数类型不正确'}";
            }
            return returnJson;
        }

    }
}
